package cn.windy.samary.module.admin.controller;

import cn.windy.samary.core.annotation.OpLog;
import cn.windy.samary.module.admin.common.Tree;
import cn.windy.samary.module.admin.entity.Permission;
import cn.windy.samary.module.Constants;
import cn.windy.samary.module.admin.service.IPermissionService;
import cn.windy.samary.module.abstracts.controller.AbstractController;
import cn.windy.samary.utils.PageContent;
import cn.windy.samary.utils.Res;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author zyl
 * @date 2018/5/21 15:24
 */
@Controller
@RequestMapping("/admin/permission")
public class PermissionController extends AbstractController {

    private String prefix = "admin/permission/";

    @Resource(name = "permissionServiceImpl")
    private IPermissionService permissionService;

    @GetMapping
    @OpLog(value = "打开权限管理界面")
    @RequiresPermissions("admin:permission:permission")
    public String index(HttpServletRequest request, HttpServletResponse response, Model model) {
        model.addAttribute("basePath", getBasePath(request));
        return prefix + "permission";
    }

    @ResponseBody
    @GetMapping(value = "/list")
    @OpLog(value = "查询权限列表")
    @RequiresPermissions("admin:permission:permission")
    public Object queryList(PageContent pageContent, String pType, String pId) {
        Example example = new Example(Permission.class);
        Example.Criteria criteria = example.createCriteria();
        example.orderBy("sort");
        if ("1".equals(pType)) {//查询菜单、按钮权限,查询树结构，不分页
            Example.Criteria criteria2 = example.createCriteria();
            criteria2.orEqualTo("type", Constants.PERM_TYPE_MENU);
            criteria2.orEqualTo("type", Constants.PERM_TYPE_BUTTON);
            example.and(criteria2);
            return permissionService.selectByExample(example);
        } else {//其他权限
            criteria.andNotEqualTo("type", Constants.PERM_TYPE_BUTTON);
            criteria.andNotEqualTo("type", Constants.PERM_TYPE_MENU);
            Page<Object> page = PageHelper.offsetPage(pageContent.getOffset(), pageContent.getLimit(), true);
            List<Permission> permissions = permissionService.selectByExample(example);
            return Res.rows(permissions, page.getTotal());
        }
    }

    @OpLog("添加权限")
    @GetMapping("add/{pId}")
    @RequiresPermissions("admin:permission:add")
    public String add(@PathVariable String pId, HttpServletRequest request, Model model) {
        model.addAttribute("pId", pId);
        if ("0".equals(pId)) {
            model.addAttribute("pName", "根节点");
        } else {
            model.addAttribute("pName", permissionService.selectByPrimaryKey(pId).getName());
        }
        return prefix + "permissionAdd";
    }

    @OpLog("编辑权限")
    @GetMapping("edit/{id}")
    @RequiresPermissions("admin:permission:edit")
    public String edit(HttpServletRequest request, Model model,
                       @PathVariable String id) {
        model.addAttribute("basePath", getBasePath(request));
        Permission permission = permissionService.selectByPrimaryKey(id);
        model.addAttribute("perm", permission);
        String pId = permission.getpId();
        model.addAttribute("pId", pId);
        if ("0".equals(pId) || StringUtils.isBlank(pId)) {
            model.addAttribute("pName", "根节点");
        } else {
            model.addAttribute("pName", permissionService.selectByPrimaryKey(pId).getName());
        }
        return prefix + "permissionEdit";
    }


    @ResponseBody
    @OpLog("保存权限")
    @PostMapping("save")
    @RequiresPermissions("admin:permission:add")
    public Object save(@Valid Permission entity) {
        int i = permissionService.insertSelective(entity);
        return i != 0 ? Res.ok() : Res.error();
    }

    @ResponseBody
    @OpLog("更新权限")
    @PutMapping("update")
    @RequiresPermissions("admin:permission:edit")
    public Object update(@Valid Permission entity) {
        int i = permissionService.updateByPrimaryKeySelective(entity);
        return i != 0 ? Res.ok() : Res.error();
    }

    @OpLog("删除权限")
    @ResponseBody
    @DeleteMapping("remove")
    @RequiresPermissions("admin:permission:remove")
    public Object remove(String id) {
        int i = permissionService.delete(id);
        return i != 0 ? Res.ok() : Res.error();
    }

    @OpLog("批量删除权限")
    @ResponseBody
    @DeleteMapping("batchRemove")
    @RequiresPermissions("admin:permission:batchRemove")
    public Object batchRemove(@RequestParam(value = "ids[]") String[] ids) {
        List<String> idsList = new ArrayList<>(Arrays.asList(ids));
        if (idsList.size() != 0) {
            permissionService.deleteByPrimaryKeys(idsList);
        }
        return Res.ok();
    }

    @GetMapping("/tree")
    @ResponseBody
    public Tree<Permission> tree() {
        Tree<Permission> tree = permissionService.getTree();
        return tree;
    }

    @GetMapping("/tree/{roleId}")
    @ResponseBody
    public Tree<Permission> tree(@PathVariable("roleId") String roleId) {
        Tree<Permission> tree = permissionService.getTree(roleId);
        return tree;
    }
}
